package com.nnnu.orange.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.orange.constant.StatusConstants;
import com.nnnu.orange.exception.ObjectException;
import com.nnnu.orange.mapper.BorrowingsMapper;
import com.nnnu.orange.mapper.PaymentsMapper;
import com.nnnu.orange.pojo.entity.Borrowings;
import com.nnnu.orange.pojo.entity.Payments;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class BorrowingTask {

    private final BorrowingsMapper borrowingsMapper;
    private final PaymentsMapper paymentsMapper;
    private static final BigDecimal DAILY_FINE = new BigDecimal("0.5");


    /**
     * 每天19:00定时任务
     */
    @Scheduled(cron = "0 0 19 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void auditBorrowingRecords() {
        // 查询所有借阅中的记录
        List<Borrowings> borrowingsList = borrowingsMapper.selectList(
                new LambdaQueryWrapper<Borrowings>().eq(Borrowings::getStatus, 1) // 状态1表示借阅中
        );

        LocalDateTime today = LocalDateTime.now();

        for (Borrowings borrowing : borrowingsList) {
            // 如果到期日期早于今天，则为逾期
            if (borrowing.getDueDate().isBefore(today)) {
                // 更新状态为逾期 (status = 0)
                borrowing.setStatus(StatusConstants.ZERO);

                // 增加罚款金额，每天罚款 0.5
                BigDecimal currentFine = borrowing.getFine() == null ? BigDecimal.ZERO : borrowing.getFine();
                borrowing.setFine(currentFine.add(DAILY_FINE));

                // 更新借阅记录
                int updateResult = borrowingsMapper.updateById(borrowing);
                if (updateResult < 1) {
                    throw new ObjectException("更新逾期记录失败，借阅ID: " + borrowing.getBorrowingId());
                }

                // 查询订单表，检查是否已有相关记录
                Payments existingPayment = paymentsMapper.selectOne(new LambdaQueryWrapper<Payments>()
                        .eq(Payments::getBorrowingId, borrowing.getBorrowingId())
                        .eq(Payments::getUserId, borrowing.getUserId())
                );

                if (existingPayment != null) {
                    // 如果订单已存在，则更新罚款金额
                    BigDecimal newFineAmount = existingPayment.getFineAmount().add(borrowing.getFine());
                    existingPayment.setFineAmount(newFineAmount);

                    // 更新订单表中的罚款金额
                    int updatePaymentResult = paymentsMapper.updateById(existingPayment);
                    if (updatePaymentResult < 1) {
                        throw new ObjectException("更新订单罚款金额失败，订单ID: " + existingPayment.getId());
                    }
                } else {
                    // 如果订单不存在，插入一条新记录
                    Payments newPayment = new Payments();
                    newPayment.setUserId(borrowing.getUserId());
                    newPayment.setBorrowingId(borrowing.getBorrowingId());
                    newPayment.setFineAmount(borrowing.getFine()); // 逾期罚款金额
                    newPayment.setStatus(StatusConstants.ZERO); //
                    newPayment.setPaidDate(null); // 未支付

                    int insertPaymentResult = paymentsMapper.insert(newPayment);
                    if (insertPaymentResult < 1) {
                        throw new ObjectException("插入逾期订单记录失败，借阅ID: " + borrowing.getBorrowingId());
                    }
                }
            }
        }
    }

}
